let util = require('../../utils/util.js');
let api = require('../../config/api.js');
let user = require('../../utils/user.js');

let app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    finalMoney: 0,
    subtractMoney: 0,
    allChecked: true
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // wx.showLoading();
    let that = this;
    util.request(api.CartList).then(function(res) {
      if (res.code === 0) {
        that.setData({
          cartList: res.data
        });
        that.calTotalPrice();
        that.checkAllSelected();
      }
    });
    user.getCartCount();
  },

  /**
   * 去结算
   */
  toFirmOrder: function() {
    let cartList = this.data.cartList,
      cartIds = [];
    cartList.forEach(cart => {
      if (cart.checked) {
        cartIds.push(cart.id)
      }
    })
    if (!cartIds.length) {
      wx.showToast({
        title: '请选择商品',
        icon: "none"
      })
      return
    }
    wx.setStorageSync("cartIds", cartIds.join(','));
    wx.navigateTo({
      url: '/pages/order/checkout/checkout?orderEntry=0',
    })
  },

  /**
   * 全选
   */
  onSelAll: function() {
    let that=this
    ,allChecked = this.data.allChecked
    ,cartList = this.data.cartList;
    allChecked = !allChecked; //改变状态

    for (let i = 0; i < cartList.length; i++) {
      let cItems = cartList[i];
      cItems.checked = allChecked;
    }

    wx.showLoading();
    util.request(api.CartUpdateAll, {
      checked: allChecked
    }, 'POST').then(function (res) {
      if (res.code == 0) {
        that.setData({
          allChecked: allChecked,
          cartList: cartList
        });
        that.calTotalPrice(); //计算总价
      }
      wx.hideLoading();
    });
  },

  /**
   * 每一项的选择事件
   */
  onSelectedItem: function(e) {
    let that=this
    ,index = e.currentTarget.dataset.index // 获取data- 传进来的index
    ,cartList = this.data.cartList // 获取购物车列表
    ,checked = cartList[index].checked; // 获取当前商品的选中状态
    cartList[index].checked = checked == 0 ? 1 : 0; // 改变状态
    wx.showLoading();
    util.request(api.CartUpdate, {
      id: cartList[index].id,
      checked: cartList[index].checked
    }, 'POST').then(function (res) {
      if (res.code == 0) {
        that.setData({
          cartList: cartList
        });
      }
      wx.hideLoading();
    });
    this.checkAllSelected(); //检查全选状态
    this.calTotalPrice(); //计算总价
  },

  /**
   * 检查全选状态
   */
  checkAllSelected: function() {
    let allChecked = true;
    let cartList = this.data.cartList;

    for (let i = 0; i < cartList.length; i++) {
      if (!cartList[i].checked) {
        allChecked = !allChecked;
        break;
      }
    }
    this.setData({
      allChecked: allChecked
    });
  },

  /**
   * 计算购物车总额
   */
  calTotalPrice: function() {
    let cartList = this.data.cartList,
      finalMoney = 0;
    for (let i = 0; i < cartList.length; i++) {
      let cart = cartList[i];
      if (cart.checked) {
        finalMoney += cart.price * cart.number;
      }
    }
    this.setData({
      finalMoney: finalMoney
    });
  },

  /**
   * 减少数量
   */
  onCountMinus: function(e) {
    let index = e.currentTarget.dataset.index;
    let cart = this.data.cartList[index];
    if (cart.number > 1) {
      this.updateCount(cart, index, -1);
    }
  },

  /**
   * 增加数量
   */
  onCountPlus: function(e) {
    let index = e.currentTarget.dataset.index;
    let cart = this.data.cartList[index];
    this.updateCount(cart, index, 1);
  },


  /**
   * 改变购物车数量接口
   */
  updateCount: function(cart, index, number) {
    let that = this;
    cart.number += number;
    wx.showLoading({
      mask: true
    });
    util.request(api.CartUpdate, {
      id: cart.id,
      number: cart.number
    }, 'POST').then(function(res) {
      let cartList = that.data.cartList;
      cartList[index] = cart;
      if (res.code == 0) {
        that.setData({
          cartList: cartList
        });
        that.calTotalPrice();
        let cartCount = app.globalData.cartCount + number;
        wx.setTabBarBadge({
          index: 1,
          text: cartCount + "",
        })
        app.globalData.cartCount = cartCount;
      }
      wx.hideLoading();
    });
  },

  /**
   * 删除购物车商品
   */
  onDelCart: function() {
    let that = this,
      cartList = this.data.cartList;

    let cartIds = cartList.map(function(element, index, array) {
      if (element.checked == true) {
        return element.id;
      }
    });

    if (cartIds.length == 0) {
      wx.showToast({
        title: '请选择商品',
        icon: "none"
      })
    } else {
      wx.showModal({
        title: '',
        content: '确认要删除选中的商品吗？',
        confirmColor: "#eb2444",
        success(res) {
          if (res.confirm) {
            wx.showLoading({
              mask: true
            });

            util.request(api.CartDelete, {
              cartIds: cartIds
            }, 'POST').then(function(res) {
              if (res.code === 0) {
                wx.hideLoading();
                that.onShow();
                user.getCartCount();
              }
            });
          }
        }
      });
    }
  }
})